
const urlParse = require("./urlParse");
const axios = require("axios");
const cheerio = require("cheerio");
const S = require("underscore.string");


function getIdInfoFromUrl (url) {
    let parsedUrl = urlParse(url);
    let qUserId = Number(parsedUrl.param["userId"]);
    let qWorksId = Number(parsedUrl.param["photoId"]);
    let segment = parsedUrl.segment;
    let pUserId = Number(segment[segment.length - 2]);
    let pWorksId = Number(segment[segment.length - 1]);
    return {
        userId: qUserId || pUserId,
        worksId: qWorksId || pWorksId
    };
}
function getBasePageUrl () {
    return "http://www.kuaishou.com";
}
function buildAccessUrl (userId, worksId) {
    return getBasePageUrl() + "/photo/" + userId + "/" + worksId;
}
function convertUrl (url) {
    let idInfo = getIdInfoFromUrl(url);
    if (idInfo.userId && idInfo.worksId) {
        return buildAccessUrl(idInfo.userId, idInfo.worksId);
    }
    else {
        return null;
    }
}
async function $getPage (url) {
    let response = await axios.get(url);
    return cheerio.load(response.data.toString());
}
async function $getKuaiShouPage (url) {
    let accessUrl = convertUrl(url);
    return await $getPage(accessUrl);
}

function convertKuaishouAccount (getText) {
    let startText = "快手号:";
    if (S(getText).startsWith(startText)) {
        return getText.slice(startText.length, getText.length);
    }
    else {
        return getText;
    }
}
function convertKuaishouNumber (getText) {
    getText = getText.toLowerCase();
    let str = S(getText);
    let unit = 1;
    if (str.endsWith("w")) {
        unit *= 10000;
        getText = getText.slice(0, getText.length - 1);
    }
    else if (str.endsWith("k")) {
        unit *= 1000;
        getText = getText.slice(0, getText.length - 1);
    }
    getText = getText.trim();
    return Number(getText) * unit;
}

function convertKuaishouTime (getText) {
    
}

function getUserInfo ($page) {
    let $totalInfo = $page(".total-info");

    let nickName = $totalInfo.children("h2").text();
    let nickNameHtml = $totalInfo.children("h2").html();
    let kuaishouAccount = convertKuaishouAccount($totalInfo.children("p").text());


    let $workInfo = $totalInfo.children(".work-info");
    let $divs = $workInfo.children("div");
    let fansNum = convertKuaishouNumber($divs.eq(0).find("p.num").text());
    let followNum = convertKuaishouNumber($divs.eq(1).find("p.num").text());
    let worksNum = convertKuaishouNumber($divs.eq(2).find("p.num").text());

    let $a = $totalInfo.find(".img-wrap > a");
    let kuaiShouUserUrl = $a.attr("href");
    let pathArray = kuaiShouUserUrl.split("/");
    let kuaishouId = pathArray[pathArray.length - 1];
    let headImgUrl = $a.find("img").attr("src");

    return {
        kuaishouId: kuaishouId,
        nickName: nickName,
        nickNameHtml: nickNameHtml,
        kuaishowAccount: kuaishouAccount,
        fansNum: fansNum,
        followNum: followNum,
        worksNum: worksNum,
        headImgUrl: headImgUrl
    };
}
function getWorksInfo ($page) {
    let $videoWarp = $page(".video-wrap");

    let videoUrl = $videoWarp.find("video").attr("src");

    let $desc = $videoWarp.find(".desc");

    let $userWords = $desc.find(".user-words");
    let time = $userWords.find(".user-name > span").text();
    let comment = $userWords.find(".words > p").text();
    let commentHtml = $userWords.find(".words > p").html();

    let $commentsNum = $desc.find(".comments-num");
    let commentNum = convertKuaishouNumber($commentsNum.children("span").eq(0).text());
    let likeNum = convertKuaishouNumber($commentsNum.children("span").eq(1).text());
    let playNum = convertKuaishouNumber($commentsNum.children("span").eq(2).text());
    let shareNum = convertKuaishouNumber($commentsNum.children("span").eq(3).text());

    return {
        videoUrl: videoUrl,
        time: time,
        comment: comment,
        commentHtml: commentHtml,
        commentNum: commentNum,
        likeNum: likeNum,
        playNum: playNum,
        shareNum: shareNum
    }
}
function getCommentsInfo ($page) {
    let commentList = [];

    let $commentArea = $page(".comment-area");
    let $commentList = $commentArea.children(".comment-wrap");
    for (let i = 0; i < $commentList.length; ++i) {
        let $comment = $commentList.eq(i);
        let headUrl = $comment.children("img").attr("src");
        let nickName = $comment.find(".user-name").children("strong").text();
        let nickNameHtml = $comment.find(".user-name").children("strong").html();
        let time = $comment.find(".user-name").children("span").text();
        let content = $comment.find(".words").children("p").text();
        let contentHtml = $comment.find(".words").children("p").html();

        commentList[i] = {
            headUrl: headUrl,
            nickName: nickName,
            nickNameHtml: nickNameHtml,
            time: time,
            content: content,
            contentHtml: contentHtml
        };
    }

    return commentList;
}
function getOtherWorksInfo ($page) {
    let $photoList = $page(".photo-list");

    let rtv = [];

    let $aArray = $photoList.find("li > a");
    for (let i = 0; i < $aArray.length; ++i) {
        let $a = $aArray.eq(i);
        let pagePath = $a.attr("href");
        let imgCss = $a.css("background-image");
        let op = imgCss.indexOf("http");
        let ed = imgCss.lastIndexOf(")");
        let imgUrl = imgCss.slice(op, ed);

        let pathList = pagePath.split("/");
        let worksId = pathList[pathList.length - 1];
        let kuaishouId = pathList[pathList.length - 2];

        rtv[i] = {
            kuaishouId: kuaishouId,
            worksId: worksId,
            pageUrl: getBasePageUrl() + pagePath,
            imgUrl: imgUrl
        };
    }

    return rtv;
}


let obj = async function (url) {
    let $page = await $getKuaiShouPage(url);

    let userInfo = null;
    let worksInfo = null;
    let commentsInfo = null;
    let otherWorksInfo = null;
    let idInfo = null;
    let accessUrl = null;
    
    return {
        $: () => {
            return $page;
        },
        $page: () => {
            return $page;
        },
        user: () => {
            if (!userInfo) {
                userInfo = getUserInfo($page);
            }
            return userInfo;
        },
        works: () => {
            if (!worksInfo) {
                worksInfo = getWorksInfo($page);
            }
            return worksInfo;
        },
        comments: () => {
            if (!commentsInfo) {
                commentsInfo = getCommentsInfo($page);
            }
            return commentsInfo;
        },
        otherWorks: () => {
            if (!otherWorksInfo) {
                otherWorksInfo = getOtherWorksInfo($page);
            }
            return otherWorksInfo;
        },
        kuaishouId: () => {
            if (!idInfo) {
                idInfo = getIdInfoFromUrl(url);
            }
            return idInfo.userId;
        },
        worksId: () => {
            if (!idInfo) {
                idInfo = getIdInfoFromUrl(url);
            }
            return idInfo.worksId;    
        },
        accessUrl: function () {
            if (!accessUrl) {
                accessUrl = buildAccessUrl(this.kuaishouId(), this.worksId());
            }
            return accessUrl;
        },
        allResource: function () {

        }
    };
};

module.exports = obj;